package org.batatasframework.util;

public class BytesUtils {

	public static int toInt(byte[] bytes, int indexOf) {
		int result = 0;
		for ( int i = 0; i < 4; i++ ) {
			result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i + indexOf];
		}
		return result;
	}
	public static int toInt(byte[] bytes) {
		return toInt(bytes, 0);
	}
	public static long toLong(byte[] bytes, int indexOf) {
		if ( bytes == null ) {
			return 0;
		}
		if ( bytes.length != indexOf + 8 ) {
			throw new IllegalArgumentException( "Expecting 8 byte values to construct a long" );
		}
		long value = 0;
        for (int i=0; i<8; i++) {
			value = (value << 8) | (bytes[i + indexOf] & 0xff);
		}
		return value;
	}
	public static long toLong(byte[] bytes) {
		return toLong(bytes, 0);
	}
	public static char toChar(byte[] bytes, int indexOf) {  
        char value = (char) ((bytes[0 + indexOf] << 8) & 0xFF00L);  
        value |= (char) (bytes[1 + indexOf] & 0xFFL);  
        return value;  
	}
	public static char toChar(byte[] bytes) { 
		return toChar(bytes, 0);
    } 
	public static float toFlaot(byte[] bytes, int indexOf){
		return Float.intBitsToFloat(toInt(bytes, indexOf));
	}
	public static double toDouble(byte[] bytes, int indexOf){
		return Double.longBitsToDouble(toLong(bytes, indexOf));
	} 
	public static float toFlaot(byte[] bytes){
		return Float.intBitsToFloat(toInt(bytes, 0));
	}
	public static double toDouble(byte[] bytes){
		return Double.longBitsToDouble(toLong(bytes, 0));
	} 

	public static byte[] fromShort(int shortValue) {
		byte[] bytes = new byte[2];
		bytes[0] = (byte) ( shortValue >> 8 );
		bytes[1] = (byte) ( ( shortValue << 8 ) >> 8 );
		return bytes;
	}
	public static byte[] fromInt(int intValue) {
		byte[] bytes = new byte[4];
		bytes[0] = (byte) ( intValue >> 24 );
		bytes[1] = (byte) ( ( intValue << 8 ) >> 24 );
		bytes[2] = (byte) ( ( intValue << 16 ) >> 24 );
		bytes[3] = (byte) ( ( intValue << 24 ) >> 24 );
		return bytes;
	}
	public static byte[] fromLong(long longValue) {
		byte[] bytes = new byte[8];
		bytes[0] = (byte) ( longValue >> 56 );
		bytes[1] = (byte) ( ( longValue << 8 ) >> 56 );
		bytes[2] = (byte) ( ( longValue << 16 ) >> 56 );
		bytes[3] = (byte) ( ( longValue << 24 ) >> 56 );
		bytes[4] = (byte) ( ( longValue << 32 ) >> 56 );
		bytes[5] = (byte) ( ( longValue << 40 ) >> 56 );
		bytes[6] = (byte) ( ( longValue << 48 ) >> 56 );
		bytes[7] = (byte) ( ( longValue << 56 ) >> 56 );
		return bytes;
	}
	public static byte[] fromFloat(float floatValue){
		return fromInt(Float.floatToIntBits(floatValue));
	}
	public static byte[] fromDouble(double doubleValue){
		return fromLong(Double.doubleToLongBits(doubleValue));
	}
	public static byte[] fromChar(char c) {  
        byte[] b = new byte[8];  
        b[0] = (byte) (c >>> 8);  
        b[1] = (byte) c;  
        return b;  
    }  
}
